﻿using Microsoft.EntityFrameworkCore;
using RecordBill.Common;
using RecordBill.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RecordBill.Data
{
   public class ImportService
    {
        // === 保存到数据库 ===
        public async Task SaveToDatabaseAsync(List<Transaction> transactions)
        {
            using var context = new AppDbContext();

            // 确保数据库和表存在
            await context.Database.EnsureCreatedAsync();

            // 检查是否有重复的微信单号（可选）
            var existingIds =  context.Transactions
                .Where(t => transactions.Select(x => x.TransactionId).Contains(t.TransactionId))
                .Select(t => t.TransactionId).ToHashSet();
                

            var newTransactions = transactions
                .Where(t => !string.IsNullOrEmpty(t.TransactionId) && !existingIds.Contains(t.TransactionId))
                .ToList();

            if (newTransactions.Count == 0)
            {
                Console.WriteLine("所有记录已存在于数据库中，无需插入。");
                return;
            }

            Console.WriteLine($"准备插入 {newTransactions.Count} 条新记录到数据库...");

            // 批量插入
            await context.Transactions.AddRangeAsync(newTransactions);
            await context.SaveChangesAsync();

            Console.WriteLine($"成功插入 {newTransactions.Count} 条新记录。");
        }

        public PageResult<UIBillStatisticsInfo> QueryBillItems(PageQueryBill query)
        {
            if (query.PageIndex <=0) query.PageIndex = 1;
            if (query.PageSize <= 0) query.PageSize = 15;
            var where = PredicateBuilder.True<Transaction>();
            if(query.StartTime.HasValue)
            {
                where = where.And(a => a.TradeTime >= query.StartTime.Value);
            }
            if(query.EndTime.HasValue)
            {
                where = where.And(a => a.TradeTime <= query.EndTime.Value);
            }


            using var context = new AppDbContext();

            var list = context.Transactions.Where(where).Skip((query.PageIndex-1) * query.PageSize).Take(query.PageSize).ToList();
            var totalMoney = context.Transactions.Where(where).AsEnumerable().Sum(a => a.Amount);
            var totalCount = context.Transactions.Count(where);
            var billInfo = new UIBillStatisticsInfo()
            {
                BillItemList = list,
                SumMoney= totalMoney,
            };

            var result = new PageResult<UIBillStatisticsInfo>()
            {
                TotalCount = totalCount,
                Data = billInfo
            };
            return result;
        }
        public async Task<List<Transaction>> QueryAllBillItems(PageQueryBill query)
        {
            using var context = new AppDbContext();
            var where = PredicateBuilder.True<Transaction>();
            if (query.StartTime.HasValue)
            {
                where = where.And(a => a.TradeTime >= query.StartTime.Value);
            }
            if(query.EndTime.HasValue)
                where = where.And(a => a.TradeTime <= query.EndTime.Value);
            var list = await context.Transactions.Where(where).ToListAsync();
            return list;
        }
    }
}
